<template>
    <div class="audio-container">
        <div class="audio-controller" :class="{bgc: audioData.job}">
            <div class="play-btn" :class="{'adjust-pr': audioData.job}" @click="notice()">
                <img :src="playImage">
            </div>
            <div class="play-controller" :class="{'adjust-pr': audioData.job}">
                <div class="title">{{title}}</div>
                <div class="controller">
                    <div class="start" v-if="!audioData.job">{{notime}}</div>
                    <div class="duration">
                        <div class="duration-container" :class="{'job-audio': !audioData.name}">
                            <slider @change="midChange"  @changing="midChangeing" activeColor="#ff927e" block-size="12" min="0" :value="nowmiao" :max="allmiao" class="slider" block-color="#ff927e"/>
                            <!-- <div class="tiao" ref="tiaobar" @tap="clClick" :style="{width}">
                                <div class="tiaotop" :style="width"></div>
                                <div class="cl" :style="midwidth" @touchstart="clstart" @touchmove="clmove" @touchend="clend">
                                    <div class="cl-mid">
                                        <img :src="midIcon" alt="">
                                    </div>
                                </div>
                            </div> -->
                        </div>
                    </div>
                    <div class="end">{{alltime}}</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    components: {},
    // props: ['audioSrc', 'title', 'playState','audioIndex'],
    props: ["audioData","close"],
    data() {
        return {
            task: {},
            durationWidth: 0,
            durationLeft: 0,
            winWidth: 0,
            audioCtx: null,
            currentLyric: null,
            currentLineNum: 0,
            toLineNum: -1,
            isfirst: false,
            allmiao: 1,
            midshow: true,
            lyricArr: [],
            height: 0,
            nowmiao: 0,
            offsetWidth: 0,
            touch: {
                time: 0,
                initiated: true,
                startX: 0,
                setWidth: 0
            },

            audioSrc: "",
            title: "",
            playState: null,
            // 是否在投的配那个
            moveFlag : false,
            // 记录拖动完的帧数
            moveNum : 0,
        };
    },
    onUnload() {
        this.audioData.play = 0;
        this.audioPause()
    },
    handleTap(e) {
        console.log('事件',e)
    },
    watch: {
        // 'playState' (val) {
        //     console.log(val);
        //     if (val) {
        //         this.audioPlay();
        //     } else {
        //         if (this.audioCtx != null) {
        //             this.audioCtx.pause();
        //         }
        //     }
        // }
        audioData: {
            handler: function(val,oldval) {
                this.$nextTick(() => {
                    
                    // console.log('深度监听',val,oldval)
                    if (val.duration) {
                        this.allmiao = val.duration || 0;
                    }
                    if (val.play === 1) {
                        if (this.audioCtx != null) {
                            this.audioPlay();
                        } else {
                            this.startInit();
                            console.log('音频播放器2')
                        }
                    } else {
                        if (this.audioCtx != null) {
                            // this.audioCtx.pause();
                            this.audioPause()
                            console.log("监听暂停");
                        } else {
                            // this.audioCtx = null;
                            // this.startInit();
                        }
                    }

                    if (val.content != oldval.content && oldval.content != null) {
                        this.startInit()
                        // this.audioSrc = this.audioData.content;
                        // this.title = this.audioData.name
                        //     ? this.audioData.name
                        //     : "";
                        // this.allmiao = this.audioData.duration || 0;
                        // this.playState = false;
                        // this.audioCtx = null;
                        // setTimeout(() => {
                        //     // 初始化
                        //     this.init();
                        // }, 50);
                    }
                });
            },
            deep: true
        },
        close: {
            handler: function(val) {
                console.log('子组件监听暂停',val)
                if (val && val != null) {
                   
                    this.$emit('closeAudioWatch',true)
                }
            },
            deep: true
        }
    },
    computed: {
        width() {
            return (
                "width:" +
                this.nowmiao / this.allmiao * this.durationWidth +
                "px"
            );
        },
        midwidth() {
            return (
                "transform:translate3d(" +
                (this.nowmiao / this.allmiao * this.durationWidth).toFixed(1) +
                "px,0px,1px);transform:translate3d(" +
                (this.nowmiao / this.allmiao * this.durationWidth).toFixed(1) +
                "px,0px,1px);"
            );
        },
        midValue () {
            return parseInt(this.nowmiao / this.allmiao * this.durationWidth)
        },
        notime() {
            return this.formact(this.allmiao <= this.nowmiao ? this.allmiao: this.nowmiao  );
        },
        alltime() {
            return this.formact(this.allmiao);
        },
        playImage() {
            let src = "";
            if (this.title) {
                src = this.audioData.play
                    ? "http://mobuz-mp.gz.bcebos.com/matter/post_audio_pause_icon.png"
                    : "http://mobuz-mp.gz.bcebos.com/matter/post_audio_playback.png";
            } else {
                src = this.audioData.play
                    ? "http://mobuz-mp.gz.bcebos.com/matter/record_pause_icon.png"
                    : "http://mobuz-mp.gz.bcebos.com/matter/homework_audio_playback.png";
            }

            return src;
        },
        midIcon() {
            let src = "";
            if (this.title) {
                src = "http://mobuz-mp.gz.bcebos.com/matter/post_schedule.png";
            } else {
                src =
                    "http://mobuz-mp.gz.bcebos.com/matter/homework_schedule.png";
            }
            return src;
        }
    },
    mounted() {
        this.allmiao = this.audioData.duration || 0;
        if (!this.audioData.job) {
            this.startInit();
        }
        console.log('音频播放器1')
    },
    methods: {
        midChange (e) {
            console.log('拖动结束',e.target.value)
            this.nowmiao = Math.floor(e.target.value);
            const miao = Math.floor(e.target.value);
            this.moveNum =  Math.floor(e.target.value);
            if (this.nowmiao >= this.allmiao) {
                this.playState = 0;
                this.audioData.play = 0;
                this.audioCtx.seek(0);
                this.audioPause()
            } else {
                // this.audioCtx.play();
                // this.audioCtx.pause();
                // this.audioCtx.play()
                
                this.audioCtx.seek(miao);
                if(this.audioData.play === 1) {
                    this.audioCtx.play()
                    this.setTime(miao)
                }
              
               
            }
        },
        midChangeing (e) {
            console.log('拖动中',e.target.value)
            this.audioPause()

        },
        // 通知 是否播放
        notice() {
            console.log(this.audioData);
            // 通知父组件，用户点击了我
            // this.$emit("audioeNotice",{audioIndex:this.audioIndex,title: this.title ? this.title:'' } );
            this.$emit("audioeNotice", this.audioData);
        },
        startInit() {
            this.audioSrc = this.audioData.content;
            this.title = this.audioData.name ? this.audioData.name : "";
            this.playState = this.audioData.play;
            this.allmiao = this.audioData.duration || 0;
            setTimeout(() => {
                // 初始化
                this.init();
            }, 50);
        },
        // 设置开始时间
        setTime (t) {
            let num = t || 0;
            clearInterval(this.audioTimer)
            this.audioTimer = setInterval(()=> {
                if (this.allmiao <= this.nowmiao) {
                    clearInterval(this.audioTimer)
                    this.audioPause()
                    this.nowmiao = 0;
                    this.audioData.play = 0;
                } else {
                    this.nowmiao = num;
                    num++;
                    console.log('开始中')
                }
                
            },1000)
        },
        // 初始化
        init() {
            // console.log(this.audioCtx,'............audio对象');
            if (this.audioCtx != null) {
                this.audioCtx.stop()
                this.audioCtx.destroy()
            }
            let self = this;
            this.audioCtx = wx.createInnerAudioContext();
            if (!this.audioSrc) return false;
            this.audioCtx.src = this.audioSrc; //设置src
            // 即使用户打开了静音开关，也能继续发出声音
            this.audioCtx.obeyMuteSwitch = false
            // 获取音频进度条的宽度
            var query = wx.createSelectorQuery();
            let obj = query
                .select( self.audioData.name ? ".duration-container" : '.job-audio')
            if (!obj)  return false;
            obj
                .boundingClientRect(rect => {
                    if (rect === null) {
                        return false;
                    }
                    self.durationLeft = rect.left;
                    self.durationWidth = rect.width;
                    // that.setData({
                    //     height: rect.width + "px"
                    // });
                })
                .exec();    
            this.winWidth = wx.getSystemInfoSync().windowWidth; //屏幕总宽
            // console.log('获取到的音频时长',this.allmiao)
            if (!this.allmiao) {
                let num = 0;
                const a = setInterval(() => {
                    this.allmiao = this.audioCtx.duration;
                    console.log(this.allmiao, "播放时长");
                    if (this.allmiao) {
                        clearInterval(a);
                    };
                    if (num >= 20) {
                         clearInterval(a);
                    } else {
                        num++;
                    }
                }, 300);
            };
            this.audioCtx.onCanplay(() => {
                console.log("ok了", this.audioCtx.currentTime);
                // this.audioCtx.pause();
                if (this.audioData.play) {
                    this.audioPlay();
                    // this.audioCtx.play();
                }
            });
            this.audioCtx.onTimeUpdate(()=>{
                //update  Progress bar
                console.log(this.audioCtx.duration,'......时间更新')
            })
        },
        //...省略
        formact(current) {
            let interval = current | 0;
            let minute = (interval / 60) | 0;
            let num = interval % 60;
            let len = num.toString().length;
            while (len < 2) {
                num = "0" + num;
                len++;
            }
            return minute + ":" + num;
        },
        // 音频播放
        audioPlay() {
            console.log("音频播放", this.audioCtx.paused);
            if (this.audioData.play === 1) {
                // 拉到尾部不播放
                if (this.nowmiao >= this.allmiao) {
                    this.nowmiao = 0;
                    this.audioCtx.seek(0);
                    this.audioData.play = 0;
                    this.audioPause()
                } else {
                    // 播放
                    this.audioCtx.play();
                    this.setTime(this.nowmiao)
                }
            } 
        },
        // 音频暂停
        audioPause () {
            this.audioCtx.pause();
            clearInterval(this.audioTimer)
        },
        handleLyric(currentTime) {
            let lines = [{ time: 0, txt: "" }],
                lyric = this.currentLyric,
                lineNum;
            lines = lines.concat(lyric.lines);
            for (let i = 0; i < lines.length; i++) {
                if (i < lines.length - 1) {
                    let time1 = lines[i].time,
                        time2 = lines[i + 1].time;
                    if (currentTime > time1 && currentTime < time2) {
                        lineNum = i - 1;
                        break;
                    }
                } else {
                    lineNum = lines.length - 2;
                }
            }
            (this.currentLineNum = lineNum),
                (this.currentText =
                    lines[lineNum + 1] && lines[lineNum + 1].txt);
            let toLineNum = lineNum - 5;
            if (lineNum > 5 && toLineNum != this.toLineNum) {
                this.toLineNum = toLineNum;
            }
        }
    }
};
</script>

<style lang="less" scoped>
.audio-container {
    .audio-controller {
        width: 100%;
        height: 120rpx;
        background-color: #fafafa;
        border: 1rpx solid #e2e2e2;
        border-radius: 8rpx;
        display: flex;
        &.bgc {
            background-color: #fdfdfd;
        }
        .play-btn {
            text-align: left;
            // flex-basis: 114rpx;
            display: flex;
            align-items: center;
            padding: 0 14rpx 0 20rpx;
            &.adjust-pr {
                padding-right: 28rpx;
            }
            img {
                vertical-align: middle;
                width: 80rpx;
                height: 80rpx;
                display: block;
                border-radius: 50%;
                overflow: hidden;
            }
        }
        .play-controller {
            padding-right: 43rpx;
            width: 100%;
            height: 120rpx;
            // flex-grow: 0;
            // flex-shrink: 0;
            flex-basis: auto;
            &.adjust-pr {
                padding-right: 22rpx;
            }
            .title {
                padding-top: 25rpx;
                padding: 25rpx 0 21rpx;
                line-height: 1;
                padding-left: 15rpx;
                font-family: PingFangSC-Regular;
                font-size: 26rpx;
                color: #333333;
                letter-spacing: 1.2rpx;
            }
            .controller {
                display: flex;
                .start,
                .end {
                    flex-basis: 62rpx;
                    font-family: PingFangSC-Regular;
                    font-size: 22rpx;
                    color: #666666;
                    letter-spacing: 0.61rpx;
                }
                .end {
                    text-align: right;
                }
                .duration {
                    // margin-top: 17rpx;
                    padding: 0 17rpx;
                    width: 100%;
                    height: 26rpx;
                    display: flex;
                    align-items: center;
                    .duration-container {
                        width: 100%;
                        height: 26rpx;
                        padding: 0 4rpx;
                        .slider {
                            display: block;
                            margin: 0 auto;
                            vertical-align: top;
                        }
                        .tiao {
                            margin: 0 auto;
                            border-radius: 25rpx;
                            height: 2rpx;
                            border-radius: 1rpx;
                            background: #adaaa8;
                            position: relative;
                            font-size: 0;
                            transform:translate3d(0px,0px,1px);
                            -webkit-transform:translate3d(0px,0px,1px);
                            .tiaotop {
                                transform:translate3d(0px,0px,1px);
                                -webkit-transform:translate3d(0px,0px,1px);
                                border-radius: 1rpx;
                                height: 2rpx;
                                // background: #d44439;
                                border-radius: 25rpx;
                                background-image: linear-gradient(
                                    -180deg,
                                    #ffb497 0%,
                                    #fe7a72 100%
                                );
                            }
                            .cl {
                                position: absolute;
                                top: -12rpx;
                                bottom: 0;
                                left: -13rpx;
                                right: 0;
                                height: 26rpx;
                                width: 26rpx;
                                .cl-mid {
                                    top: 17rpx;
                                    left: 10rpx;
                                    box-sizing: border-box;
                                    width: 26rpx;
                                    height: 26rpx;
                                    border-radius: 50%;
                                    // border: 5px solid #f1f1f1;
                                    z-index: 10;
                                    // background-image: linear-gradient(
                                    //     -180deg,
                                    //     #ffb497 0%,
                                    //     #fe7a72 100%
                                    // );
                                    overflow: hidden;
                                    img {
                                        display: block;
                                        width: 26rpx;
                                        height: 26rpx;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>
